package il.ac.tau.cvws.scrabblesidekick.client.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import android.os.Environment;

/* Utility for accessing the device's storage. This abstraction
 * allows the application to store and retrieve storage-units, and specifically
 * in this case the calibration-key.
 */
public class FileUtil
{
	/* Store the given object in the specified directory, as a file with the given name.
	 */
	public static void storeObject(Serializable obj, String dir, String name) throws IOException
	{
		File root = new File(Environment.getExternalStorageDirectory(), dir);
        
		if (!root.exists()) 
        {
            root.mkdirs();
        }

        File file = new File(root, name);
        
        FileOutputStream fos   = null;
        ObjectOutputStream oos = null;
        
        try
        {
        	fos = new FileOutputStream(file);
            oos = new ObjectOutputStream(fos);
            
            oos.writeObject(obj);
            oos.flush();
        }
        finally
        {
        	if (fos != null)
        	{
        		fos.close();
        	}
        	
        	if (oos != null)
        	{
        		oos.close();
        	}
        }
	}
	
	/* Retrive the file with the given name from the given directory.
	 */
	public static Object getObject(String dir, String name) throws IOException, ClassNotFoundException
	{
		StringBuilder sb = new StringBuilder();
		sb.append(Environment.getExternalStorageDirectory()).append("/").append(dir).append("/").append(name);
		
		File file = new File(sb.toString());
		
        FileInputStream fis   = null;
        ObjectInputStream ois = null;
        
        try
        {
        	fis = new FileInputStream(file);
            ois = new ObjectInputStream(fis);
            
            Object result = ois.readObject();
            
            return result;
        }
        finally
        {
        	if (fis != null) fis.close();
        	if (ois != null) ois.close();
        }
	}
}
